﻿using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Systems;
using george.Web;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static BaseAPI.model.DictData;

namespace BaseAPI.SysBaseInfo
{
    [Description("系统数据字典")]
    public class SysDictHandler : BaseHandler
    {
        [MustLogin]
        [Description("系统数据字典列表")]
        [ReturnType(typeof(IList<PageDictList>))]
        public ApiResult GetTreeList(int ParentId=1)
        {
            var cacheKey = "all-Dict-list";
            var allDictList = myCache.Get<IList<PageDictList>>(cacheKey);
            if (allDictList == null)
            {
                allDictList = GetChildren(ParentId);
                myCache.Set(cacheKey, allDictList);
            }
            return Success(allDictList);
        }

        /// <summary>
        /// 获取子菜单
        /// </summary>
        /// <param name="parnetID"></param>
        /// <returns></returns>
        public List<PageDictList> GetChildren(int parentId)
        {
            var dc = new SysEntities();
            var query = from c in dc.sys_dictionary
                        where c.ParentId== parentId && c.isRemove == false
                        select c;
            return (from c in query select c).ToList().Select(t => new PageDictList
            {
                ID = t.ID,
                DictName = t.dictName,
                DictValue = t.dictValue,
                IsRemove = t.isRemove,
                ParentId = t.ParentId,
                Memo = t.Memo,
                Childrens = GetChildren((int)t.ID)
            }).ToList();
        }

        [MustLogin]
        [Description("字典明细")]
        [ReturnType(typeof(SysDictData))]
        public ApiResult GetId([ParamDescription("ID")]int ID)
        {
            var dc = new SysEntities();
            var query = dc.sys_dictionary.FirstOrDefault(t=>t.ID==ID);
            if (query == null) return Error("无数据");
            var result = new SysDictData
            {
                DictName = query.dictName,
                DictValue = query.dictValue,
                ID = query.ID,
                IsRemove = query.isRemove,
                Memo = query.Memo,
                ParentId = query.ParentId,
                SystemIdentifier = query.SystemIdentifier,
            };
            return Success(result);
        }

        [MustLogin]
        [Description("字典列表")]
        [ReturnType(typeof(IList<SysDictData>))]
        public ApiResult GetList([ParamDescription("ID")]string DictValue="")
        {
            var dc = new SysEntities();
            var data = dc.sys_dictionary.FirstOrDefault(t => t.dictValue == DictValue && t.isRemove == false);
            if (data==null) return Error("无数据");
            var query = dc.sys_dictionary.Where(t => t.ID == data.ID || t.ParentId == data.ID && t.isRemove == false);
            var result = query.ToList().Select(t => new SysDictData
            {
                DictName = t.dictName,
                DictValue = t.dictValue,
                ID = t.ID,
                IsRemove = t.isRemove,
                Memo = t.Memo,
                ParentId = t.ParentId,
                SystemIdentifier = t.SystemIdentifier,
            }).ToList();
            return Success(result);
        }
        
        [JsonType]
        [Description("新增字典信息")]
        [ReturnType(typeof(int), "0－成功")]
        public ApiResult Create([ParamDescription("输入参数")]SysDictData param)
        {
            if (param == null) return Error("参数对象为空");
            if (string.IsNullOrWhiteSpace(param.DictName)) return Error("模块名称不能为空");
            if (!string.IsNullOrWhiteSpace(param.Memo))
                if (param.Memo.Length > 50) return Error("【说明】长度超出限制");
            var dc = new SysEntities();
            if (dc.sys_dictionary.Any(t => t.dictName == param.DictName && t.isRemove == false))
                return Error($"【{param.DictName}】已存在");
            if (dc.sys_dictionary.Any(t => t.dictValue == param.DictValue && t.ParentId==param.ParentId && t.isRemove == false))
                return Error($"字典值【{param.DictValue}】已存在");
            var dict = new sys_dictionary
            {
                Memo = param.Memo,
                dictValue = param.DictValue,
                ParentId = param.ParentId,
                dictName = param.DictName,
                isRemove=false,
                SystemIdentifier=param.SystemIdentifier,
            };
            dc.sys_dictionary.Add(dict);
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [JsonType]
        [Description("修改字典信息")]
        [ReturnType(typeof(int), "0－成功")]
        public ApiResult Modify([ParamDescription("输入参数")]SysDictData param)
        {
            if (param == null) return Error("参数对象为空");
            if (string.IsNullOrWhiteSpace(param.DictName)) return Error("模块名称不能为空");
            if (!string.IsNullOrWhiteSpace(param.Memo))
                if (param.Memo.Length > 50) return Error("【说明】长度超出限制");
            var dc = new SysEntities();
            if (dc.sys_dictionary.Any(t => t.dictName == param.DictName && t.isRemove == false && t.ID != param.ID))
                return Error($"【{param.DictName}】已存在");
            if (dc.sys_dictionary.Any(t => t.dictValue == param.DictValue && t.ParentId == param.ParentId
            && t.isRemove == false && t.ID != param.ID))
                return Error($"字典值【{param.DictValue}】已存在");
            var query = dc.sys_dictionary.FirstOrDefault(t => t.ID == param.ID);
            if (query == null) return Error("无数据");
            var queryConDicValue = dc.sys_config.FirstOrDefault(r => r.dictValue == query.dictValue);
            var queryConValue = dc.sys_config.FirstOrDefault(r => r.Value == query.dictValue);
            query.Memo = param.Memo;
            query.dictValue = param.DictValue;
            query.ParentId = param.ParentId;
            query.dictName = param.DictName;
            query.SystemIdentifier = param.SystemIdentifier;
            if (!(queryConDicValue == null))
            {
                queryConDicValue.dictValue = query.dictValue;
            }
            if (!(queryConValue == null))
            {
                queryConValue.Value = query.dictValue;
            }
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [MustLogin]
        [Description("移除字典数据")]
        [ReturnType(typeof(int), "0－成功")]
        public ApiResult Remove([ParamDescription("ID")] int ID)
        {
            var dc = new SysEntities();
            var query = dc.sys_dictionary.FirstOrDefault(t => t.ID == ID);
            if (query == null) return Error("无数据");
            //逻辑删除
            query.isRemove = true;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }
    }
}
